#!/usr/bin/env python
# coding=utf-8
#
#  Created by Skiloop
#  Email: skiloop@126.com
#
import cv2
import numpy as np
from PIL import Image


def filter_channel(img, channel):
    assert len(img.shape) == 3 == img.shape[2] and 0 <= channel < 3
    nm = np.empty(img.shape, dtype=np.uint8)
    nm[:, :, channel] = img[:, :, channel]
    return nm


def filter_image(ifs, ofs, channel=0):
    img = cv2.imread(ifs)
    cv2.imwrite(ofs, filter_channel(img, channel))


def color_status(img):
    colors = {}
    h, w, d = img.shape
    for i in range(0, w):
        for j in range(0, h):
            color = img[j, i, :]
            if color not in colors:
                color[color] = []
            colors[color].append((j, i))
    return colors


def gif2jpg(ifs, ofs):
    img = Image.open(ifs)
    rgb = img.convert('RGB')
    rgb.save(ofs)


def ic_two_pass(binim):
    """
    两遍扫描法查找连通区域
    :param binim: 输入的二值图片
    :return:
    """
    if binim is None:
        return
    r, c = binim.shape
    label_img = np.copy(binim)
    if label_img.max() > 1:
        for i in range(0, r):
            for j in range(0, c):
                label_img[i, j] = 1 if label_img[i, j] > 0 else 0
    label = 1
    label_set = [0, 1]
    label_map = []
    for i in range(0, r):
        pre_row = i - 1
        cur_row = i
        for j in range(0, c):
            if 1 == label_img[cur_row, j]:
                neighbor_labels = []
                if j > 0:
                    left_pixel = label_img[cur_row, j - 1]
                else:
                    left_pixel = 0
                if pre_row >= 0:
                    up_pixel = label_img[pre_row, j]
                else:
                    up_pixel = 0
                if left_pixel > 1:
                    neighbor_labels.append(left_pixel)
                if up_pixel > 1:
                    neighbor_labels.append(up_pixel)
                if len(neighbor_labels) == 0:
                    label += 1
                    label_set.append(label)
                    label_img[cur_row, j] = label
                    label_map.append((i, j, label))
                else:
                    neighbor_labels.sort()
                    smallest_label = neighbor_labels[0]
                    if isinstance(smallest_label, tuple):
                        pass
                    label_img[cur_row, j] = smallest_label
                    label_map.append((i, j, smallest_label))
                    if len(neighbor_labels) > 1:
                        if label_set[neighbor_labels[1]] > smallest_label:
                            label_set[neighbor_labels[1]] = smallest_label
                        elif label_set[neighbor_labels[1]] < smallest_label:
                            label_set[smallest_label] = label_set[neighbor_labels[1]]
        # print label_img, label_set

    idx = 2
    while idx < len(label_set):
        cur_label = label_set[idx]
        while cur_label != label_set[cur_label]:
            cur_label = label_set[cur_label]
        label_set[idx] = cur_label
        idx += 1
    for i in range(0, r):
        for j in range(0, c):
            label_img[i, j] = label_set[label_img[i, j]]
    return label_img, label_set, label_map


if __name__ == '__main__':
    d = [[0, 0, 1, 0, 0, 1, 0], [1, 1, 1, 0, 1, 1, 1], [0, 0, 1, 0, 0, 1, 0], [0, 1, 1, 0, 1, 1, 0]]
    na = np.asarray(d)
    no, nl, lm = ic_two_pass(na)
    print no
    print nl
    print lm
